<template>
  <div class="role-card-list">
    <!-- 头部 -->
    <div class="list-header">
      <div class="header-title">
        <UserOutlined class="header-icon" />
        <span class="title-text">选择角色</span>
      </div>
      <div class="header-actions">
        <a-button 
          type="text" 
          size="small" 
          @click="refreshRoles"
          :loading="loading"
          class="refresh-btn"
        >
          <template #icon>
            <ReloadOutlined />
          </template>
        </a-button>
      </div>
    </div>

    <!-- 搜索 -->
    <div class="search-filter-section">
      <div class="search-container">
        <a-input
          v-model:value="searchKeyword"
          placeholder="搜索角色名称、描述..."
          size="medium"
          class="search-input"
          @input="handleSearch"
        >
          <template #prefix>
            <SearchOutlined class="search-icon" />
          </template>
        </a-input>
      </div>
    </div>

    <!-- 角色卡片列表 -->
    <div class="roles-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <a-spin size="large" />
        <div class="loading-text">加载角色中...</div>
      </div>

      <!-- 角色卡片网格 -->
      <div v-else-if="filteredRoles.length > 0" class="roles-grid">
        <div
          v-for="role in filteredRoles"
          :key="role.id"
          class="role-card"
          @click="selectRole(role)"
        >
          <div class="role-avatar">
            <a-avatar 
              :size="48" 
              :src="role.avatarUrl || role.avatar"
              :style="{ 
                background: role.avatarUrl || role.avatar ? 'transparent' : 'linear-gradient(135deg, #6366f1, #8b5cf6)',
                fontSize: '20px',
                fontWeight: '600'
              }"
            >
              {{ !role.avatarUrl && !role.avatar ? (role.roleName?.[0] || 'R') : '' }}
            </a-avatar>
          </div>
          
          <div class="role-info">
            <h3 class="role-name">{{ role.roleName }}</h3>
            <p class="role-description">{{ role.prompt }}</p>
            
            <div class="role-tags">
              <!-- 音色标签 -->
              <a-tag
                v-if="role.voiceId"
                size="small"
                color="purple"
                class="role-tag voice-tag"
              >
                <template #icon>
                  <span class="voice-icon">🎵</span>
                </template>
                {{ getVoiceName(role.voiceId) }}
              </a-tag>
               <!-- 原有标签 -->
                <a-tag
                v-for="tag in (role.tags || []).slice(0, 1)"
                :key="tag"
                size="small"
                :color="getTagColor(tag)"
                class="role-tag"
              >
                {{ tag }}
              </a-tag>
              <!-- 知识库标签 -->
              <a-tag
                v-if="role.knowledgeId"
                size="small"
                color="blue"
                class="role-tag knowledge-tag"
              >
                <template #icon>
                  <span class="knowledge-icon">📚</span>
                </template>
                {{ getKnowledgeName(role.knowledgeId) }}
              </a-tag>
              
              <!-- 分类标签 -->
              <!-- <a-tag :color="getCategoryColor(role.category || '')" size="small" class="role-tag">
                {{ getCategoryLabel(role.category || '') }}
              </a-tag>
               -->
             
            
              
            </div>
          </div>
          
          <!-- 默认角色标识 -->
          <div v-if="role.isDefault" class="default-role-badge">
            <a-tag color="gold" size="small">
              <template #icon>
                <StarFilled />
              </template>
              默认
            </a-tag>
          </div>
        </div>
      </div>

      <div v-else class="empty-state">
        <UserOutlined class="empty-icon" />
        <div class="empty-text">
          {{ searchKeyword ? '未找到匹配的角色' : '暂无可用角色' }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { UserOutlined, SearchOutlined, ReloadOutlined, StarFilled } from '@ant-design/icons-vue'
import { useResourceStore } from '@/stores'
import type { KnowledgeBaseListVO } from '@/api/generated/data-contracts'
import { Codewin } from '@/api/generated/Codewin'
import { useAuthStore } from '@/stores/modules/auth'

// 定义角色类型
interface Role {
  id: string
  roleName: string
  prompt: string
  avatarUrl?: string
  avatar?: string
  category?: string
  era?: string
  tags?: string[]
  isDefault?: boolean
  createAt?: string
  voiceId?: string
  knowledgeId?: string
}

// Props
interface Props {
  roles: Role[]
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

// Emits
const emit = defineEmits<{
  selectRole: [role: Role]
  refresh: []
}>()

// 响应式数据
const searchKeyword = ref('')
const knowledgeBases = ref<KnowledgeBaseListVO[]>([])
const authStore = useAuthStore()
const resourceStore = useResourceStore()

// 计算属性
const filteredRoles = computed(() => {
  let filtered = props.roles

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(role =>
      (role.roleName || '').toLowerCase().includes(keyword) ||
      (role.prompt || '').toLowerCase().includes(keyword) ||
      (role.tags || []).some(tag => tag.toLowerCase().includes(keyword))
    )
  }

  // 如果没有搜索关键词，显示默认角色 + 前3个自创建角色
  if (!searchKeyword.value) {
    // 分离默认角色和自创建角色
    const defaultRoles = filtered.filter(role => role.isDefault)
    const customRoles = filtered.filter(role => !role.isDefault)
    
    // 取前3个自创建角色
    const limitedCustomRoles = customRoles.slice(0, 3)
    
    // 合并：默认角色在前，然后是自创建角色
    return [...defaultRoles, ...limitedCustomRoles]
  }

  // 有搜索关键词时，限制显示前12个角色
  return filtered.slice(0, 12)
})

// 方法
const selectRole = (role: Role) => {
  emit('selectRole', role)
}

const refreshRoles = () => {
  emit('refresh')
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

// const getCategoryColor = (category: string) => {
//   const colors: Record<string, string> = {
//     historical: 'orange',
//     fictional: 'purple',
//     philosopher: 'blue',
//     scientist: 'green',
//     writer: 'red'
//   }
//   return colors[category] || 'default'
// }

// const getCategoryLabel = (category: string) => {
//   const labels: Record<string, string> = {
//     historical: '历史人物',
//     fictional: '虚构角色',
//     philosopher: '哲学家',
//     scientist: '科学家',
//     writer: '作家'
//   }
//   return labels[category] || category
// }

// 获取标签颜色
const getTagColor = (tag: string) => {
  const tagColors: Record<string, string> = {
    '默认': 'blue',
    '自定义': 'green',
    '推荐': 'orange',
    '热门': 'red',
    '经典': 'purple'
  }
  return tagColors[tag] || 'default'
}

// 获取知识库名称
const getKnowledgeName = (knowledgeId: string) => {
  // 首先在普通知识库中查找
  const knowledgeBase = knowledgeBases.value.find(kb => String(kb.id) === knowledgeId)
  if (knowledgeBase) {
    return knowledgeBase.name || `知识库-${knowledgeId}`
  }
  
  // 如果普通知识库中找不到，则使用resourceStore的allKnowledgeBasesMap查找（包含默认知识库）
  const allKnowledgeBase = resourceStore.allKnowledgeBasesMap.get(knowledgeId)
  return allKnowledgeBase?.name || `知识库-${knowledgeId}`
}

// 获取音色名称
const getVoiceName = (voiceId: string) => {
  return resourceStore.getVoiceName(voiceId)
}

// 创建带认证头的API配置
const createAuthHeaders = () => {
  const token = authStore.token
  return token ? { Authorization: `Bearer ${token}` } : {}
}

// 加载知识库列表
const loadKnowledgeBases = async () => {
  try {
    const api = new Codewin({
      baseURL: import.meta.env.VITE_API_BASE_URL || '/api'
    })
    const response = await api.getKnowledgeBaseList(
      {
        pageNo: 1,
        pageSize: 100
      },
      {
        headers: createAuthHeaders()
      }
    )
    
    if (response.data?.code === 0 && response.data.data?.list) {
      knowledgeBases.value = response.data.data.list
    }
  } catch (error) {
    console.error('加载知识库列表失败:', error)
  }
}

// 组件挂载时初始化
onMounted(() => {
  loadKnowledgeBases()
  resourceStore.initResource()
})
</script>

<style scoped>
.role-card-list {
  flex: 1;
  height: 100%;
  background: #fff;
  display: flex;
  flex-direction: column;
}

/* 头部 */
.list-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  color: #6366f1;
  font-size: 16px;
}

.title-text {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
}

.header-actions {
  display: flex;
  align-items: center;
}

.refresh-btn {
  color: #666;
  transition: color 0.2s ease;
}

.refresh-btn:hover {
  color: #6366f1;
}

/* 搜索区域 */
.search-filter-section {
  padding: 16px 20px;
  /* border-bottom: 1px solid #f0f0f0; */
  background: #fafafa;
}

.search-input {
  border-radius: 6px;
}

.search-icon {
  color: #999;
}

/* 角色容器 */
.roles-container {
  flex: 1;
  overflow-y: auto;
  background: #fafafa;
  /* 滚动条样式优化 */
  scrollbar-width: thin;
  scrollbar-color: #d1d5db #f9fafb;
}

/* Webkit浏览器滚动条样式 */
.roles-container::-webkit-scrollbar {
  width: 6px;
}

.roles-container::-webkit-scrollbar-track {
  background: #f9fafb;
  border-radius: 3px;
}

.roles-container::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 3px;
  transition: background-color 0.2s ease;
}

.roles-container::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

.roles-container::-webkit-scrollbar-thumb:active {
  background: #6b7280;
}

/* 滚动条角落 */
.roles-container::-webkit-scrollbar-corner {
  background: #f9fafb;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  gap: 16px;
}

.loading-text {
  color: #666;
  font-size: 14px;
}

/* 角色卡片网格 */
.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 16px;
  width: 100%;
  padding: 20px;
}

.role-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  min-height: 180px;
}

.role-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border-color: #6366f1;
}

.role-avatar {
  flex-shrink: 0;
  margin-bottom: 12px;
}

.role-info {
  flex: 1;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.role-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  text-align: center;
}

.role-description {
  margin: 0 0 12px 0;
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-align: center;
  width: 100%;
}

.role-meta {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.role-era {
  font-size: 12px;
  color: #999;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
  justify-content: center;
}

.role-tag {
  font-size: 12px !important;
  border-radius: 4px !important;
}

.more-tags {
  font-size: 12px;
  color: #999;
}

/* 默认角色标识 */
.default-role-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 1;
}

/* 音色标签样式 */
.voice-tag {
  background: linear-gradient(135deg, #a855f7, #c084fc) !important;
  border: none !important;
  color: white !important;
}

.voice-icon {
  margin-right: 4px;
  font-size: 12px;
}

/* 知识库标签样式 */
.knowledge-tag {
  background: linear-gradient(135deg, #3b82f6, #60a5fa) !important;
  border: none !important;
  color: white !important;
}

.knowledge-icon {
  margin-right: 4px;
  font-size: 12px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #d9d9d9;
}

.empty-text {
  font-size: 14px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .roles-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .roles-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .roles-container {
    padding: 16px;
  }
  
  .search-filter-section {
    padding: 12px 16px;
  }
  
  .list-header {
    padding: 12px 16px;
  }
}
</style>